<?php
namespace Admin\Model;
use Think\Model;

class PsortModel extends Model{
	//自动验证
	protected $_validate = array(
		array('name','1,20','分类名称不得为空或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('color','1,20','分类颜色不得大于20位！',self::VALUE_VALIDATE,'length'),
	);
	
	//查询总记录
	public function total(){
		return $this->where($this->map())->count();
	}
	
	//查询所有
	public function all($firstRow){
		return $this->field('id,name,color,sort,date')
    				->where($this->map())
    				->order(array('sort'=>'ASC'))
    				->limit($firstRow,C('PAGE_SIZE'))
    				->select();
	}
	
	//查询所有（不分页）
	public function all2($ids=0){
		$map = array();
		if ($ids) $map['id'] = array('IN',$ids);
		return $this->field('id,name,color')
    				->where($map)
    				->order(array('sort'=>'ASC'))
    				->select();
	}
	
	//查询一条
	public function one($id=0){
		$map['id'] = $id ? $id : I('get.id');
		return $this->field('name,color')->where($map)->find();
	}
	
	//添加
	public function insert(){
		$data = array(
			'name'=>I('post.name'),
			'color'=>I('post.color'),
			'sort'=>$this->nextId(),
			'date'=>NOW_TIME
		);
		if ($this->create($data)){
			if ($this->repeat()) return '此产品分类已存在！';
			$id = $this->add();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//修改
	public function update(){
		$data = array(
			'id'=>I('get.id'),
			'name'=>I('post.name'),
			'color'=>I('post.color')
		);
		if ($this->create($data)){
			if ($this->repeat(1)) return '此产品分类已存在！';
			$id = $this->save();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//排序
	public function sort($id,$sort){
		$data = array(
			'id'=>$id,
			'sort'=>$sort
		);
		return $this->save($data);
	}
	
	//删除
	public function remove(){
		$affected_rows = $this->delete(I('get.id'));
		if ($affected_rows) $this->execute('OPTIMIZE TABLE `__PREFIX__psort`');
		return $affected_rows;
	}
	
	//验证重复
	private function repeat($type=0){
		$map = array('name'=>I('post.name'));
		if ($type) $map['id'] = array('NEQ',I('get.id'));
		return $this->field('id')->where($map)->find();
	}
	
	//自增ID
	private function nextId(){
		$object = $this->query("SHOW TABLE STATUS FROM `".C('DB_NAME')."` LIKE '__PREFIX__psort'");
		return $object[0]['Auto_increment'];
	}
	
	//搜索
	private function map(){
		$map = array(
			'_complex'=>array(
				'name'=>array('like','%'.I('get.keyword').'%'),
				'_logic'=>'OR'
			)
		);
		return $map;
	}
}